<template>
  <view class="echarts-container">
    <canvas 
      canvas-id="pieChart" 
      id="pieChart" 
      class="pie-canvas"
      :style="{ width: width + 'px', height: height + 'px' }"
    ></canvas>
  </view>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'EchartsPie',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    width: {
      type: Number,
      default: 200
    },
    height: {
      type: Number,
      default: 200
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    data: {
      handler(newData) {
        this.$nextTick(() => {
          this.initChart()
        })
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  methods: {
    initChart() {
      if (!this.data || this.data.length === 0) return
      
      // 转换数据格式
      const seriesData = this.data.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: {
          color: item.color
        }
      }))
      
      const option = {
        backgroundColor: 'transparent',
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            data: seriesData,
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      // 使用uni-app的canvas API
      const query = uni.createSelectorQuery().in(this)
      query.select('#pieChart')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res[0] && res[0].node) {
            const canvas = res[0].node
            const ctx = canvas.getContext('2d')
            
            // 设置canvas尺寸
            const dpr = uni.getSystemInfoSync().pixelRatio
            canvas.width = this.width * dpr
            canvas.height = this.height * dpr
            ctx.scale(dpr, dpr)
            
            // 创建ECharts实例
            this.chart = echarts.init(canvas, null, {
              width: this.width,
              height: this.height,
              devicePixelRatio: dpr
            })
            
            // 设置配置项
            this.chart.setOption(option)
          } else {
            // 如果获取不到node，延迟重试
            setTimeout(() => {
              this.initChart()
            }, 200)
          }
        })
    }
  }
}
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pie-canvas {
  width: 100%;
  height: 100%;
}
</style> 